<template>
	<view class="container">
		<uni-search-bar @cancel="cancel" @confirm="search" :focus="true" v-model="searchValue">
		</uni-search-bar>

		<uni-grid :column="1">
			<uni-grid-item v-for="po in posts" :key="po.id">
				<navigator :url="`/pages/details/details?title=${po.title}&post_id=${po.id}`">
					<text class="text">{{po.title}}</text>
				</navigator>
			</uni-grid-item>
		</uni-grid>
	</view>
</template>

<script setup>
	import {
		onLoad,
		onPullDownRefresh,
		onReachBottom,
	} from '@dcloudio/uni-app';
	// ------------
	import {
		ref
	} from 'vue';

	import {
		getPostsApi
	} from '../../api/index.js'

	const ctg_id = ref('');
	const posts = ref([]);
	const is_hot = ref(false);

	const searchValue = ref('');

	const page = ref(1);
	const totalPages = ref(0);


	function search() {
		if (searchValue.value === '') return;
		getPosts();
	}

	function cancel() {
		searchValue.value = '';
		getPosts();
	}

	onLoad((e) => {
		ctg_id.value = e.ctg_id;

		switch (e.is_hot) {
			case 'true':
				is_hot.value = true;
				break;
			case 'false':
				is_hot.value = false;
				break;
			default:
				is_hot.value = '';
		}
		uni.setNavigationBarTitle({
			title: e.title,
		})
		getPosts();
	})

	async function getPosts() {

		let ctg = `ctg='${ctg_id.value}'`;
		let hot = '';
		let title = '';
		if (is_hot.value !== '') {
			hot = `&&is_hot=${is_hot.value}`
		}
		if (searchValue.value) {
			title = `&&title~'${searchValue.value}'`
		}
		const filter = `(${ctg}${hot}${title})`;
		const res = await getPostsApi({
			filter,
			page: page.value
		});
		posts.value.push(...res.data.items);
		totalPages.value = res.data.totalPages;
	}

	onPullDownRefresh(async () => {
		page.value = 1;
		posts.value = [];
		await getPosts();
		uni.stopPullDownRefresh();
	});

	onReachBottom(async () => {
		// console.log('hello');
		if (page.value < totalPages.value) {
			page.value++;
			await getPosts();
		}
	})
</script>

<style>
	.container {
		padding: 20px;
		/* 	font-size: 14px;
		line-height: 24px; */
	}
</style>